/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yutel.biz;

import com.yutel.util.Account;
import com.yutel.util.Applation;
import com.yutel.util.DBUtil;
import com.yutel.util.Preference;
import com.yutel.util.ServletProcess;
import java.io.IOException;

/**
 *
 * @author yuanyajun
 */
public class Login {

    DBUtil dbUtil = new DBUtil();

    public boolean login(String username, String password, boolean auto) {
        boolean result = true;
        try {
            StringBuffer para = new StringBuffer();
            para.append("username=").append(username);
            para.append("password=").append(password);
            String results = ServletProcess.request(para.toString());
            // TODO:
            if (auto && result) {
                Applation app = Applation.getInstance();
                app.setUsername(username);
                app.setPassword(password);
                Account account = new Account(username, password);
                dbUtil.saveAccount(account, 1);
                Preference p = dbUtil.getPreference(2);
                if (p == null) {
                    p = new Preference();
                }
                p.setAutoLogin(auto);
                dbUtil.savePreference(p, 2);
            }
            return result;
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        }
    }

    public boolean autoLogin() {
        boolean result = true;
        try {
            Account a = dbUtil.getAccount(1);
            if (a != null) {
                StringBuffer para = new StringBuffer();
                para.append("username=").append(a.getUsername());
                para.append("password=").append(a.getPassword());
                String results = ServletProcess.request(para.toString());
                // TODO:
                Applation app = Applation.getInstance();
                app.setUsername(a.getUsername());
                app.setPassword(a.getPassword());
            } else {
                result = false;
            }
            return result;
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        }
    }

    public boolean logout(String username) {
        try {
            StringBuffer para = new StringBuffer();
            para.append("username=").append(username);
            String result = ServletProcess.request(para.toString());
            Preference p = dbUtil.getPreference(2);
            if (p != null) {
                p.setAutoLogin(false);
                dbUtil.savePreference(p, 2);
            }
            return true;
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        }
    }
}
